#include <windows.h>

#include "world.h"

LPCWSTR lpszAppName = L"noname";

World *world = NULL;


void setDCPixelFormat(HDC hdc)
{
	int pixelFormat;
	static PIXELFORMATDESCRIPTOR pfd = 
	{
		sizeof(PIXELFORMATDESCRIPTOR),
		1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA,
		32,
		0,0,0,0,0,0,
		0,0,
		0,0,0,0,0,
		16,
		0,
		0,
		0,
		0,
		0,0,0
	};

	pixelFormat = ChoosePixelFormat(hdc, &pfd);
	SetPixelFormat(hdc, pixelFormat, &pfd);
}


LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	static HGLRC hRC = NULL;
	static HDC hDC = NULL;
	switch(message)
	{
	case WM_CREATE:
		hDC = GetDC(hWnd);
		setDCPixelFormat(hDC);
		hRC = wglCreateContext(hDC);
		wglMakeCurrent(hDC, hRC);
		SetTimer(hWnd, 33, 1, NULL);
		world = new World;
		break;
	case WM_DESTROY:
		KillTimer(hWnd, 101);
		wglMakeCurrent(hDC, NULL);
		wglDeleteContext(hRC);
		delete world;
		PostQuitMessage(0);
		break;
	case WM_SIZE:
		world->resize(LOWORD(lParam), HIWORD(lParam));
		break;
	case WM_TIMER:
		world->update();
		InvalidateRect(hWnd,NULL, FALSE);
		break;
	case WM_PAINT:
		world->draw();
		SwapBuffers(hDC);
		ValidateRect(hWnd, NULL);
		break;
	}
	return DefWindowProc(hWnd, message, wParam, lParam);
}


int APIENTRY WinMain (
    __in HINSTANCE hInstance,
    __in_opt HINSTANCE hPrevInstance,
    __in_opt LPSTR lpCmdLine,
    __in int nShowCmd
    )
{
	MSG msg;
	WNDCLASS wc;
	HWND hWnd;

	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wc.lpfnWndProc = (WNDPROC) WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = NULL;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = lpszAppName;

	if (RegisterClass(&wc) == 0)
		return FALSE;

	hWnd = CreateWindow(
		lpszAppName,
		lpszAppName,
		WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
		100, 100,
		250, 250,
		NULL,
		NULL,
		hInstance,
		NULL);
	if (hWnd == NULL)
		return FALSE;
	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);
	while(GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return msg.wParam;
}